<template>
    <a-form :form="form" @submit="handleSubmit">
        <a-form-item v-bind="formItemLayout" label="购买者姓名">
            <a-input v-decorator="buyerNameRule" :disabled="!editModel"/>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="联系电话1">
            <a-input v-decorator="phone1Rule" type="phone" :disabled="!editModel"/>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="联系电话2">
            <a-input v-decorator="phone2Rule" type="phone" :disabled="!editModel"/>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="使用者姓名">
            <a-input v-decorator="userNameRule" :disabled="!editModel"/>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="使用者性别">
            <a-select placeholder="请选择性别" v-decorator="sexRule" :disabled="!editModel">
                <a-select-option value="男">男</a-select-option>
                <a-select-option value="女">女</a-select-option>
            </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="生辰">
            <a-date-picker v-decorator="['birthday']" format="YYYY-MM-DD" :disabled="!editModel"></a-date-picker>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="亡辰（灵位专用）">
            <a-date-picker v-decorator="['deathday']" format="YYYY-MM-DD" :disabled="!editModel"></a-date-picker>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="常用地址">
            <a-input v-decorator="['address']" :disabled="!editModel"/>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="备注">
            <a-input v-decorator="['remarks']" :disabled="!editModel"/>
        </a-form-item>
        <a-form-item v-bind="tailFormItemLayout" v-if="editModel">
            <a-button @click="backHandler">返回</a-button>
            <a-button type="primary" html-type="submit" v-if="!modifyModel && !isModal">添加客户</a-button>
            <a-button type="primary" html-type="submit" v-if="modifyModel">更新客户</a-button>
        </a-form-item>
        <a-form-item v-bind="tailFormItemLayout" v-if="!editModel">
            <a-button @click="backHandler">返回</a-button>
            <a-button type="primary" @click="modifyHandler">修改</a-button>
        </a-form-item>
    </a-form>
</template>

<script>
import { Modal } from 'ant-design-vue';
import moment from 'moment';
export default {
    name: 'add-user',
    props: ['isModal'],
    data() {
        return {
            editModel: false,
            modifyModel: false,
            formItemLayout: {
                labelCol: {
                    xs: { span: 6 },
                    sm: { span: 6 }
                },
                wrapperCol: {
                    xs: { span: 16 },
                    sm: { span: 16 }
                }
            },
            tailFormItemLayout: {
                wrapperCol: {
                    xs: {
                        span: 24,
                        offset: 0
                    },
                    sm: {
                        span: 16,
                        offset: 8
                    }
                }
            },
            buyerNameRule: [
                'buyerName',
                {
                    rules: [{ required: true, message: '请输入购买者姓名' }]
                }
            ],
            userNameRule: ['userName'],
            sexRule: ['sex'],
            phone1Rule: [
                'phone1',
                {
                    rules: [
                        { required: true, message: '请输入联系电话' },
                        {
                            pattern: /^1(3|4|5|6|7|8)\d{9}$/,
                            message: '请输入正确的手机号码'
                        }
                    ]
                }
            ],
            phone2Rule: [
                'phone2',
                {
                    rules: [
                        {
                            pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/,
                            message: '请输入正确的电话号码'
                        }
                    ]
                }
            ],
            currentUser: {},
            userId: ''
        };
    },
    beforeCreate() {
        this.form = this.$form.createForm(this);
    },
    created() {
        this.userId = this.$route.query.id;
        switch (this.$route.name) {
            case 'AddUser':
                this.editModel = true;
                break;
            case 'ModifyUser':
                this.editModel = true;
                this.modifyModel = true;
                break;
            case 'UserDetail':
                this.editModel = false;
                break;
            default:
                this.editModel = true;
        }
        if (this.userId) {
            this.$store.dispatch('getUserById', this.userId).then(user => {
                this.currentUser = user;
                this.form.setFieldsValue({
                    buyerName: this.currentUser.buyerName,
                    userName: this.currentUser.userName,
                    sex: this.currentUser.sex,
                    birthday: this.currentUser.birthday
                        ? moment(this.currentUser.birthday)
                        : undefined,
                    deathday: this.currentUser.deathday
                        ? moment(this.currentUser.deathday)
                        : undefined,
                    address: this.currentUser.address,
                    phone1: this.currentUser.phone1,
                    phone2: this.currentUser.phone2,
                    remarks: this.currentUser.remarks
                });
            });
        }
    },
    methods: {
        handleSubmit(e) {
            e.preventDefault();
            this.form.validateFieldsAndScroll((err, values) => {
                if (!err) {
                    if (this.modifyModel) {
                        Object.assign(this.currentUser, values);
                        this.$store
                            .dispatch('updateUser', this.currentUser)
                            .then(res => {
                                Modal.success({
                                    title: '更新成功',
                                    onOk: () => {
                                        this.$router.replace({
                                            name: 'UserList'
                                        });
                                    }
                                });
                            })
                            .catch(reason => {
                                console.log(reason);
                                Modal.error({
                                    title: '更新失败',
                                    onOk: () => {
                                        this.$router.replace({
                                            name: 'UserList'
                                        });
                                    }
                                });
                            });
                    } else {
                        this.$store
                            .dispatch('addUser', values)
                            .then(res => {
                                Modal.success({
                                    title: '添加成功',
                                    onOk: () => {
                                        this.$router.replace({
                                            name: 'UserList'
                                        });
                                    }
                                });
                            })
                            .catch(reason => {
                                Modal.error({
                                    title: '添加失败',
                                    onOk: () => {
                                        this.$router.replace({
                                            name: 'UserList'
                                        });
                                    }
                                });
                                console.log('用户添加失败:', reason);
                            });
                    }
                }
            });
        },
        backHandler() {
            this.$router.go(-1);
        },
        modifyHandler(e) {
            e.preventDefault();
            this.editModel = true;
            this.modifyModel = true;
        }
    }
};
</script>